package com.example.gw_back_end.interceptors;

import com.example.gw_back_end.service.mongodb.TokenService;
import com.example.gw_back_end.utils.JwtUtil;
import com.example.gw_back_end.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;
    private final TokenService tokenService;

    public LoginInterceptor(JwtUtil jwtUtil, TokenService tokenService) {
        this.jwtUtil = jwtUtil;
        this.tokenService = tokenService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String pendingToken = request.getHeader("Authorization");
        if (pendingToken != null && pendingToken.startsWith("Bearer ")) {
            String token = pendingToken.substring(7);
            String rawToken = tokenService.getRawToken(token);
            try {
                if (!jwtUtil.validateToken(rawToken)) {
                    tokenService.removeToken(token);
                    response.setStatus(401);
                    throw new Exception("TokenDocument has expired");
                }
                Map<String, Object> claims = jwtUtil.parseToken(rawToken);
                ThreadLocalUtil.set(claims);
                return true;
            } catch (Exception e) {
                response.setStatus(401);
                return false;
            }
        } else {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
